var express = require('express');
var router = express.Router();
let multiparty = require("multiparty");
let path = require("path");
const goodsService = require("../service/goodsService");

//新增商品
router.post('/', async function (req, res) {
    let { name, pictures, price, description, tag } = req.body;
    let data = await goodsService.insert({name, pictures, price, description,tag });
    res.send(data);
})

//删除商品
router.delete('/:id', async function (req, res) {
    let { id } = req.params;
    let data = await goodsService.delete(id);
    res.send(data);
});

//查询所有商品
router.get('/', async function (req, res) {
    let { type, value, current, pageSize } = req.query;
    console.log(req.headers);
    let searchParams = {};
    try {
        if (value) {
            searchParams[type] = new RegExp(value, 'i');
        }
        let data = await goodsService.find({ current: current || 1, pageSize: pageSize || 20 }, searchParams);
        res.send(data);
    } catch (error) {
        console.log(error);
    }
});

//修改商品
router.put('/:id', async function (req, res) {
    let { name, pictures, price, description, tag } = req.body;
    let { id } = req.params;
    let data = await goodsService.update({ name, pictures, price, description, tag, _id: id });
    res.send(data);
});

//上传图片

router.post("/upload", function (req, res) {
    let imgPath = path.join(__dirname, "../public/images");//后端存放图片路径
  
    var form = new multiparty.Form({ uploadDir: imgPath });
    form.parse(req, function (err, fields, files) {
      /*
          console.log(fields.username[0])
          console.log(fields.password[0])
  
          Object.keys(fields).forEach(function(name) {
              console.log('got field named ' + name + "--" + fields[name] + "----" + typeof fields[name]);
          });
  
          Object.keys(files).forEach(function(name) {
              console.log(files[name]);
          });
      */
  
      if (err) {
        res.send({ code: 1, msg: "上传失败", data: err });
      } else {
        var p = files.file[0].path.substring(
          files.file[0].path.indexOf("images")
        );
        console.log(p);
        res.send({ code: 0, msg: "上传成功", data: path.basename(p) });//获取到图片名字
      }
    });
  });
module.exports = router;